/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package pagecreator;

import helpers.CreateHTML;
import helpers.CreateTBN;
import helpers.Database;
import helpers.Lookups;
import helpers.Moviename;
import helpers.NFOTableModel;
import helpers.SaxXML;
import helpers.TableCellListener;
import helpers.TextAreaRenderer;
import helpers.XMLCreator;
import helpers.xmlNFO;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

/**
 *
 * @author frank
 */
public class PageCreatorForm extends javax.swing.JFrame {

    /**
     * Creates new form PageCratorForm
     */
    public PageCreatorForm() {
        initComponents();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        scanButton = new javax.swing.JMenuItem();
        dbScanButton = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        htmlButton = new javax.swing.JMenuItem();
        nfoButton = new javax.swing.JMenuItem();
        dbUpdateButton = new javax.swing.JMenuItem();

        jFileChooser1.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Moviescan");
        setLocationByPlatform(true);
        setPreferredSize(new java.awt.Dimension(950, 700));

        jScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setMinimumSize(new java.awt.Dimension(900, 500));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(0, 0));

        jTable1.setModel(nfoModel);
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setAutoscrolls(false);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        jMenu1.setText("Scan");

        scanButton.setText("Folder Scan");
        scanButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                scanButtonActionPerformed(evt);
            }
        });
        jMenu1.add(scanButton);

        dbScanButton.setText("DB Open");
        dbScanButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbScanButtonActionPerformed(evt);
            }
        });
        jMenu1.add(dbScanButton);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");

        htmlButton.setText("Create HTML");
        htmlButton.setEnabled(false);
        htmlButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                htmlButtonActionPerformed(evt);
            }
        });
        jMenu2.add(htmlButton);

        nfoButton.setText("Write NFO");
        nfoButton.setEnabled(false);
        nfoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nfoButtonActionPerformed(evt);
            }
        });
        jMenu2.add(nfoButton);

        dbUpdateButton.setText("Update DB");
        dbUpdateButton.setEnabled(false);
        dbUpdateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbUpdateButtonActionPerformed(evt);
            }
        });
        jMenu2.add(dbUpdateButton);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 950, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void scanButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_scanButtonActionPerformed
        if (jTable1.getModel().getRowCount() !=0) {
            resetTable();
        }
        jFileChooser1.setCurrentDirectory(new File ("D:\\Downloads\\test"));
        if (jFileChooser1.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            openfolder = jFileChooser1.getSelectedFile().getAbsolutePath();
       }
        
        jFileChooser1.setVisible(true);
        try {
            this.publisher = Moviename.getInstance().DirectoryListening(openfolder);
           
            movies = new String[publisher.length][];
            int counter = 0;
            for (String publisher1 : publisher) {
                String[] movieInFolder = Moviename.getInstance().DirectoryListening(openfolder +"\\" + publisher1);
                movies[counter] = movieInFolder;
                counter ++;
            }
            
            createLinkedList();
            
            SaxXML.getInstance().ReadNFO(movieLookups); //Liest alle NFO dateien wenn vorhanden.
              
            this.dbExist = Database.GetInstance().ReadDBSingle("porn", movieLookups);
            if (this.dbExist){
                this.xmlDiffDb = Database.GetInstance().GetDBListSingle();
            }
            
            jTable1.setDefaultRenderer(Object.class, new TextAreaRenderer());
            adultParameter(this.dbExist);
            fillTable(false,this.dbExist);
            tableColumnWidth();
            actionListener();
           
            if(picturemissed.size() != 0) {
                NoPicture noPic = new NoPicture();
                noPic.fillTable(picturemissed);
                noPic.setAlwaysOnTop(true);
                noPic.setVisible(true);
            }
            

            if (!this.dbExist) {
                firstFillDB();
            }
            else {
                this.dbXML = Database.GetInstance().GetDBList();
                //database ist gelesen
            }
            
            this.htmlButton.setEnabled(true);
            this.nfoButton.setEnabled(true);

        } catch (IOException | ParserConfigurationException | SAXException | SQLException ex) {
            Logger.getLogger(PageCreatorForm.class.getName()).log(Level.SEVERE, null, ex);
        }       
    }//GEN-LAST:event_scanButtonActionPerformed

    private void htmlButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_htmlButtonActionPerformed
        try {
            CreateHTML.getInstance().create(movieLookups);
        } catch (IOException ex) {
            Logger.getLogger(PageCreatorForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(null, "Website Ready","Website",JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_htmlButtonActionPerformed

    private void nfoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nfoButtonActionPerformed
        try {
            if (this.changedMovies.size()!=0) {
                for (Lookups lookup : this.changedMovies) {
                    XMLCreator.getInstance().CreateNFOAdult(lookup.folder, lookup.movie, lookup.xmlNFO);                    
                }
                Database.GetInstance().UpdateDB("porn", this.changedMovies);
            }
        } catch (IOException | SQLException ex) {
            Logger.getLogger(PageCreatorForm.class.getName()).log(Level.SEVERE, null, ex);
        }  
        JOptionPane.showMessageDialog(null, "NFO Ready","NFO",JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_nfoButtonActionPerformed
/*
    Lesen der datenbank zum offline bearbeiten
    */
    private void dbScanButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbScanButtonActionPerformed
        try {
            this.dbRead = Database.GetInstance().ReadDB("porn");
            if (this.dbRead) {
                this.dbExist = true;
                this.dbXML = Database.GetInstance().GetDBList();
                jTable1.setDefaultRenderer(Object.class, new TextAreaRenderer());
                try {
                    fillTable(true, this.dbExist);
                } catch (IOException ex) {
                    Logger.getLogger(PageCreatorForm.class.getName()).log(Level.SEVERE, null, ex);
                }

                tableColumnWidth();
                actionListener();
                //this.dbRead = true;
                this.dbUpdateButton.setEnabled(true);
                //database ist gelesen
            } else {
                
                JOptionPane.showMessageDialog(null, "Database missed","Database",JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (IOException | SQLException ex) {
            Logger.getLogger(PageCreatorForm.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_dbScanButtonActionPerformed

    private void dbUpdateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbUpdateButtonActionPerformed
        if (this.changedMovies.size()!=0) {
            try {
                Database.GetInstance().UpdateDB("porn", this.changedMovies);
            } catch (    IOException | SQLException ex) {
                Logger.getLogger(PageCreatorForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }//GEN-LAST:event_dbUpdateButtonActionPerformed
    
    private void tableColumnWidth(){        
        int columnWidth = 0;
        int tableColumns = jTable1.getColumnCount();
        for(int column = 1; column < tableColumns; column ++){
            TableColumn textColumn = jTable1.getColumnModel().getColumn(column);
            TableCellRenderer renderer = textColumn.getHeaderRenderer();
            if (column == 1 || column == 2 || column == 3) {            
            for(int r= 0; r < jTable1.getRowCount(); r++){
                renderer = jTable1.getCellRenderer(r, column);
                Component comp = renderer.getTableCellRendererComponent(jTable1, jTable1.getValueAt(r, column), false, false, r, column);
                columnWidth = Math.max(columnWidth, comp.getPreferredSize().width);
            }
                textColumn.setPreferredWidth(columnWidth + 2);
                columnWidth = 0;
            }
            
            if (column == 8) {
                textColumn.setPreferredWidth(240);
            }
        }       
    }
    
    private void adultParameter(boolean dbRead) throws IOException, SQLException{
        LinkedList<Lookups> lookupList = null;
        LinkedList<Lookups> lookupCorretted = new LinkedList<Lookups>();
        if (dbRead){
                lookupList = this.xmlDiffDb;
            }else {
                lookupList = this.movieLookups;
            }
        for (Lookups lookup: lookupList) {
            boolean corrected = false;
            if (lookup.xmlNFO.getMpaa().equals("")){
                lookup.xmlNFO.setMpaa("R");
                corrected = true;
            }
            if (lookup.xmlNFO.getGenre().equals("")) {
                lookup.xmlNFO.setGenre("Adult");
                corrected = true;
            }
            
            if (corrected) {
                XMLCreator.getInstance().CreateNFOAdult(lookup.folder, lookup.movie, lookup.xmlNFO);
                corrected = false;
            }
            lookupCorretted.add(lookup);
        }
                
        Database.GetInstance().UpdateDB("porn", lookupCorretted);
        
        if (dbRead){
                this.xmlDiffDb = lookupCorretted;
            }else {
                this.movieLookups = lookupCorretted;
            }
    }
    
    private void resetTable(){
        DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
        model.setRowCount(0);
        this.movieLookups.clear();
        this.picturemissed.clear();
        this.changedMovies.clear();
        this.dbRead = false;
        this.nfoButton.setEnabled(false);
        this.htmlButton.setEnabled(false);
        this.dbUpdateButton.setEnabled(false);
    }
            
    private void actionListener(){
        Action action = new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent e) {
                TableCellListener tcl = (TableCellListener)e.getSource();
                int row = tcl.getRow();
                int column = tcl.getColumn();
                Lookups lookups = new Lookups();
                xmlNFO xmlChanged = new xmlNFO();
                boolean match = false;
                if (changedMovies.size() == 0) {
                    if (dbRead) {
                        lookups = dbXML.get(row);
                    } else {
                        lookups = movieLookups.get(row);
                    }
                    xmlChanged = lookups.xmlNFO;
                } else {
                    for (Lookups look : changedMovies)
                    {
                        if (look.id == column) {
                            lookups = look;
                            xmlChanged = look.xmlNFO;
                            changedMovies.remove(look);
                            match = true;
                        }
                    }
                    
                    if (!match) {
                        if (dbRead) {
                        lookups = dbXML.get(row);
                        } else {
                            lookups = movieLookups.get(row);
                        }
                        xmlChanged = lookups.xmlNFO;
                    }
                }
                
                //publisher
                if (column == 1){
                  xmlChanged.setProducer(tcl.getNewValue().toString()); 
                }
                //name
                if (column == 2){
                    xmlChanged.setTitle(tcl.getNewValue().toString());
                }
                //sortname
                if (column == 3){
                    xmlChanged.setSorttitle(tcl.getNewValue().toString());
                }
                //Genre
                if (column == 4){
                    xmlChanged.setGenre(tcl.getNewValue().toString());
                }
                //mpaa
                if (column == 5){
                    xmlChanged.setMpaa(tcl.getNewValue().toString());
                }
                //runtime
                if (column == 6){
                   xmlChanged.setRuntime(tcl.getNewValue().toString());
                }
                //year
                if (column == 7){
                    xmlChanged.setYear(tcl.getNewValue().toString());
                }
                //plot
                if (column == 8){
                    xmlChanged.setPlot(tcl.getNewValue().toString());
                }
                //language
                if (column == 9){
                   xmlChanged.setLanguage(tcl.getNewValue().toString());
                }
                
                lookups.xmlNFO = xmlChanged;
                changedMovies.add(lookups);
            }
        };
        
        TableCellListener tcl = new TableCellListener(jTable1, action);
        
    }
    
    
    private void firstFillDB() throws IOException, SQLException{
        Database.GetInstance().WriteFirstDB("porn",this.movieLookups);
    }
    
        
    private void fillTable(boolean dbFill, boolean dbRead) throws IOException {
        LinkedList<Lookups> lookupList = null;
        if (dbFill){
            lookupList = this.dbXML;
        } else {
            //xml daten aus der DB
            if (dbRead){
                lookupList = this.xmlDiffDb;
            }else {
                //xml daten aus den nfo dateien
                lookupList = this.movieLookups;
            }
        }
        
        //erssetzen des Bildes wenn keins vorhanden in der Tabellenansicht
        boolean iconExists = false;
        for (Lookups lookups : lookupList) {
            Object[] rowData;
            if(lookups.nfoExists || dbFill) {
                String icon = lookups.xmlNFO.getIcon();
                if (lookups.xmlNFO.getIcon() != null) {
                  iconExists = Moviename.getInstance().FileExist(lookups.xmlNFO.getIcon());  
                }else {
                    icon = this.getClass().getClassLoader().getResource("resources/empty.jpg").getPath();
                }
                
                if (dbFill && !iconExists) {
                    icon = this.getClass().getClassLoader().getResource("resources/empty.jpg").getPath();
                };
                
                //ERstellen des Tabellenobjectes
                rowData = new Object[] 
                        {icon,lookups.publisher,
                        lookups.xmlNFO.getTitle(),lookups.xmlNFO.getSorttitle(),
                        lookups.xmlNFO.getGenre(),
                        lookups.xmlNFO.getMpaa(),lookups.xmlNFO.getRuntime(),
                        lookups.xmlNFO.getYear(),lookups.xmlNFO.getPlot(),
                        lookups.xmlNFO.getLanguage()};
                iconExists = false;

            } else {    
                //Wenn keine einträger für das tabellenobejct vorhanden sind
                rowData = new Object[] 
                {lookups.xmlNFO.getIcon(),lookups.publisher,
                        lookups.xmlNFO.getTitle(),lookups.xmlNFO.getSorttitle(),
                        "","","","","","",""};                
            }
            this.nfoModel.addRow(rowData);
            this.nfoModel.fireTableDataChanged();
        }
    }
    
   
   
   /*
    ERstellt die LinkedList mit dem publisher, moviename, absoluten pfad zum folder
    */ 
   private void createLinkedList () throws IOException {
        int publisherCount =0;
        for(String[] movie: movies) {
            for(String mov: movie){
                Lookups lookups = new Lookups();
                lookups.publisher = publisher[publisherCount];
                lookups.movie = mov.replaceAll("'", "");                
                lookups.folder = this.openfolder + "\\" + publisher[publisherCount]+ "\\" + mov;                
                if (Moviename.getInstance().FileExist(lookups.folder+"\\folder.jpg")){
                    CreateTBN.getInstance().createSingle(lookups.folder);
                    //lookups.id = counter;
                    lookups.resizePicName = publisher[publisherCount] + "_" + mov + ".jpg";
                    movieLookups.add(lookups);                    
                }else {
                    movieLookups.add(lookups);
                    picturemissed.add(lookups);
                }           
            }
            publisherCount++;
        }    
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PageCreatorForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PageCreatorForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PageCreatorForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PageCreatorForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PageCreatorForm().setVisible(true);
            }
        });
    }
    
    private String openfolder = "";
    private String[] publisher;
    private String[][] movies;
    private LinkedList<Lookups> movieLookups = new LinkedList<Lookups>();
    private LinkedList<Lookups> picturemissed = new LinkedList<Lookups>();
    private LinkedList<Lookups> changedMovies = new LinkedList<Lookups>();
    private LinkedList<Lookups> dbXML = new LinkedList<Lookups>();
    private LinkedList<Lookups> xmlDiffDb = new LinkedList<Lookups>();
    private JComboBox genreBox;
    private JComboBox mpaaBox;
    private JComboBox languageBox;
    //private JLabel picLabel;
    private NFOTableModel nfoModel = new NFOTableModel();
    private boolean dbRead = false;
    private boolean dbExist = false;

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem dbScanButton;
    private javax.swing.JMenuItem dbUpdateButton;
    private javax.swing.JMenuItem htmlButton;
    private javax.swing.JFileChooser jFileChooser1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JMenuItem nfoButton;
    private javax.swing.JMenuItem scanButton;
    // End of variables declaration//GEN-END:variables
}
